from datetime import datetime
from app.extensions import db, redis, rq_queue
from app.models.message import Message
from app.models.user import User
from app.utils.response import APIResponse
from app.utils.redis_pubsub import publish_message
import json

class MessageService:
    @staticmethod
    def send_private_message(sender_id, receiver_id, content, message_type='text'):
        """
        发送私聊消息
        :param sender_id: 发送者ID
        :param receiver_id: 接收者ID
        :param content: 消息内容
        :param message_type: 消息类型(text/image/file/voice/video)
        :return: APIResponse
        """
        try:
            message = Message(
                sender_id=sender_id,
                receiver_id=receiver_id,
                content=content,
                message_type=message_type,
                is_group=False,
                status=0  # 0:未读, 1:已读
            )
            db.session.add(message)
            db.session.commit()
            
            # 异步处理消息推送
            rq_queue.enqueue(
                publish_message,
                message.id,
                job_timeout=5
            )
            
            return APIResponse.success(data=message.to_dict())
        except Exception as e:
            db.session.rollback()
            return APIResponse.error(message=f"发送消息失败: {str(e)}")
    
    @staticmethod
    def send_group_message(sender_id, group_id, content, message_type='text'):
        """
        发送群聊消息
        :param sender_id: 发送者ID
        :param group_id: 群组ID
        :param content: 消息内容
        :param message_type: 消息类型
        :return: APIResponse
        """
        try:
            from app.models.group import GroupMember
            # 检查用户是否在群中
            member = GroupMember.query.filter_by(
                group_id=group_id,
                user_id=sender_id
            ).first()
            
            if not member:
                return APIResponse.error(message="您不在该群中")
            
            message = Message(
                sender_id=sender_id,
                receiver_id=group_id,
                content=content,
                message_type=message_type,
                is_group=True,
                status=1  # 群消息默认已读
            )
            db.session.add(message)
            db.session.commit()
            
            # 异步处理消息推送
            rq_queue.enqueue(
                publish_message,
                message.id,
                job_timeout=5
            )
            
            return APIResponse.success(data=message.to_dict())
        except Exception as e:
            db.session.rollback()
            return APIResponse.error(message=f"发送群消息失败: {str(e)}")
    
    @staticmethod
    def get_messages(user_id, other_id, is_group=False, limit=50, offset=0):
        """
        获取消息记录
        :param user_id: 当前用户ID
        :param other_id: 对方ID(用户ID或群ID)
        :param is_group: 是否是群聊
        :param limit: 每页数量
        :param offset: 偏移量
        :return: APIResponse
        """
        try:
            if is_group:
                from app.models.group import GroupMember
                # 检查用户是否在群中
                member = GroupMember.query.filter_by(
                    group_id=other_id,
                    user_id=user_id
                ).first()
                
                if not member:
                    return APIResponse.error(message="您不在该群中")
                
                messages = Message.query.filter_by(
                    receiver_id=other_id,
                    is_group=True
                ).order_by(Message.created_at.desc()).limit(limit).offset(offset).all()
            else:
                messages = Message.query.filter(
                    ((Message.sender_id == user_id) & (Message.receiver_id == other_id)) |
                    ((Message.sender_id == other_id) & (Message.receiver_id == user_id))
                ).filter_by(is_group=False).order_by(Message.created_at.desc()).limit(limit).offset(offset).all()
            
            # 标记私聊消息为已读
            if not is_group:
                Message.query.filter_by(
                    sender_id=other_id,
                    receiver_id=user_id,
                    status=0
                ).update({'status': 1})
                db.session.commit()
            
            return APIResponse.success(data=[msg.to_dict() for msg in messages])
        except Exception as e:
            return APIResponse.error(message=f"获取消息失败: {str(e)}")
    
    @staticmethod
    def mark_as_read(message_ids, user_id):
        """
        标记消息为已读
        :param message_ids: 消息ID列表
        :param user_id: 用户ID
        :return: APIResponse
        """
        try:
            Message.query.filter(
                Message.id.in_(message_ids),
                Message.receiver_id == user_id
            ).update({'status': 1})
            db.session.commit()
            return APIResponse.success()
        except Exception as e:
            db.session.rollback()
            return APIResponse.error(message=f"标记已读失败: {str(e)}")